package com.example.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import javax.xml.stream.XMLStreamException;

public class XStreamKit {
    private String head = "";
    private XStream xs;

    public XStreamKit(XStream xs, String encoding) {
        this.xs = xs;
        this.head = "<?xml version=\"1.0\" encoding=\""+encoding+"\"?>";
    }

    public static XStreamKit getInstance(String encoding) {
        DomDriver domDriver = new DomDriver(encoding);
        XStream xStream = new XStream(domDriver);
        return new XStreamKit(xStream,encoding);
    }

    public String beanToXml(Object obj) throws XMLStreamException {
        xs.processAnnotations(obj.getClass());
        xs.aliasSystemAttribute(null, "class");
        String xmlStr = head + xs.toXML(obj);
        return xmlStr;
    }

    public <T> T xmlToBean(String xml, Class<T> clz) {
        xs.setClassLoader(clz.getClassLoader());
        xs.processAnnotations(clz);
        T obj = (T) xs.fromXML(xml);
        return obj;
    }
}
